//
//  MainViewController.m
//  HaiTongHop
//
//  Created by Nguyen Cong Huy on 12/16/14.
//  Copyright (c) 2014 Nguyen Cong Huy. All rights reserved.
//

#define ENABLE_ADS 1

#import "MainViewController.h"
#import "DataManager.h"
#import "SourceEntity.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "GADBannerView.h"
#import "MenuCell.h"
#import "UIAlertView+Disable.h"
#import "RateRequestManager.h"

#define kMenuWidth 210
#define kMenuRowIdentifier @"kMenuRowIdentifier"
#define kWwwPrefix @"www."

@interface MainViewController () <UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate, UIActionSheetDelegate, GADBannerViewDelegate> {
    UITableView* menuTableView;
    UIView* mainView;
    UIWebView* webView;
    UIBarButtonItem *backButtonItem;
//    UIBarButtonItem *forwardButtonItem;
    SourceEntity* currentSourceEntity;
    UIView* loadingView;
    UILabel* loadingLabel;
    UIActivityIndicatorView* loadingIndicator;
    UIView* refreshView;
    UIButton* refreshButton;
    GADBannerView* bannerView;
    int lastTimeShowError;
    
    BOOL isDragging;
}

@property (nonatomic) int menuSelectedIndex;

@end

@implementation MainViewController

- (instancetype)init {
    if(self = [super init]) {
        self.menuSelectedIndex = -1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [self afterViewDidLoad];
    }];
}

- (void)afterViewDidLoad {
    self.view.backgroundColor = RGBCOLOR(236, 243, 249);
    
    [UIBarButtonItem appearance].tintColor = [UIColor blackColor];
    UIBarButtonItem *menuButtonItem =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(menuButtonTouched)];
    self.navigationItem.leftBarButtonItem = menuButtonItem;
    
    backButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(backButtonTouched)];
    backButtonItem.enabled = NO;
//    forwardButtonItem =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"forward-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(forwardButtonTouched)];
//    forwardButtonItem.enabled = NO;
    UIBarButtonItem* actionButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actionButtonTouched)];
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:backButtonItem, actionButtonItem, nil]];
    
    menuTableView = [[UITableView alloc] init];
    menuTableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"menu_background_pattern"]];
    menuTableView.scrollsToTop = NO;
    menuTableView.delegate = self;
    menuTableView.dataSource = self;
    [self.view addSubview:menuTableView];
    
    mainView = [[UIView alloc] init];
    mainView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:mainView];
    
    webView = [[UIWebView alloc] init];
    webView.delegate = self;
    [mainView addSubview:webView];
    
    loadingView = [[UIView alloc] init];
    loadingView.backgroundColor = RGBACOLOR(0, 0, 0, 200);
    loadingView.alpha = 0;
    [mainView addSubview:loadingView];
    
    loadingLabel = [[UILabel alloc] init];
    loadingLabel.text = @"Đang tải ...";
    [loadingLabel sizeToFit];
    loadingLabel.textColor = [UIColor whiteColor];
    loadingLabel.font = [UIFont boldSystemFontOfSize:15];
    [loadingView addSubview:loadingLabel];
    
    refreshView = [[UIView alloc] init];
    refreshView.backgroundColor = RGBACOLOR(0, 0, 0, 200);
    refreshView.alpha = 0;
    [mainView addSubview:refreshView];
    
    refreshButton = [[UIButton alloc] init];
    [refreshButton setTitle:@"Tải lại" forState:UIControlStateNormal];
    [refreshButton addTarget:self action:@selector(refreshButtonTouched) forControlEvents:UIControlEventTouchUpInside];
    [refreshView addSubview:refreshButton];
    
    loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    [loadingIndicator startAnimating];
    [loadingView addSubview:loadingIndicator];
    
    bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait];
    bannerView.adUnitID = @"ca-app-pub-2807844358876629/9036673396";
    bannerView.rootViewController = self;
    bannerView.delegate = self;
    
#if ENABLE_ADS
    [self.view addSubview:bannerView];
    [self loadAd];
#endif
    
    [self layoutViews];
    
    [[DataManager sharedDataManager] loadRemoteSourceWithComplete:^(BOOL isNewData) {
        if(isNewData) {
            [menuTableView reloadData];
            
            [self updateMenuSelectedIndexToCurrentIndex];
        }
    }];
    
    UIPanGestureRecognizer* panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizer:)];
    [self.view addGestureRecognizer:panGesture];
    
    RateRequestManager* rateRequestManager = [RateRequestManager getInstance];
    rateRequestManager.countToAskRate = 15;
    rateRequestManager.appRateUrlString = @"https://itunes.apple.com/app/id954507564";
    [rateRequestManager updateAndShowRateRequestIfNeed];
}

- (void)layoutViews {
    menuTableView.frame = CGRectMake(0, 0, kMenuWidth, self.view.height);
    mainView.frame = CGRectMake(0, 0, self.view.width, self.view.height);
#if ENABLE_ADS
    webView.frame = CGRectMake(0, 0, mainView.width, mainView.height - kGADAdSizeBanner.size.height);
#else
    webView.frame = CGRectMake(0, 0, mainView.width, mainView.height);
#endif
    loadingView.frame = CGRectMake(0, 0, mainView.width, 64);
    loadingLabel.frame = CGRectMake(0, 0, 100, 40);
    loadingLabel.center = CGPointMake(loadingView.width/2, loadingView.height/2);
    refreshView.frame = CGRectMake(0, 0, mainView.width, 64);
    refreshButton.frame = CGRectMake(0, 0, 60, 30);
    refreshButton.center = CGPointMake(refreshView.width/2, refreshView.height/2);
    loadingIndicator.center = CGPointMake(loadingLabel.left - loadingIndicator.frame.size.width, loadingView.height/2);
    bannerView.frame = CGRectMake(0, self.view.height - bannerView.frame.size.height, self.view.width, bannerView.frame.size.height);
}

- (void)updateMenuSelectedIndexToCurrentIndex {
    if(self.menuSelectedIndex == -1) {
        self.menuSelectedIndex = 0;
    }
    else {
        self.menuSelectedIndex = self.menuSelectedIndex;
    }
    NSIndexPath* selectedRow = [NSIndexPath indexPathForRow:self.menuSelectedIndex inSection:0];
    [menuTableView selectRowAtIndexPath:selectedRow animated:YES scrollPosition:UITableViewScrollPositionNone];
}

- (void)menuButtonTouched {
    [self showHideMenu];
}

- (BOOL)isMenuShowing {
    if(mainView.left != 0) {
        return YES;
    }
    return NO;
}

- (void)showHideMenu {
        if([self isMenuShowing]) {
            [self hideMenu];
        }
        else {
            [self showMenu];
        }
}

- (void)showMenu {
    [UIView animateWithDuration:0.2 animations:^{
        CGRect mainViewFrame = mainView.frame;
        mainViewFrame.origin.x = kMenuWidth;
        mainView.frame = mainViewFrame;
    }];
}

- (void)hideMenu {
    [UIView animateWithDuration:0.2 animations:^{
        CGRect mainViewFrame = mainView.frame;
        mainViewFrame.origin.x = 0;
        mainView.frame = mainViewFrame;
    }];
}

- (void)setMenuSelectedIndex:(int)menuSelectedIndex {
    _menuSelectedIndex = menuSelectedIndex;
    
    if(self.menuSelectedIndex >= 0) {
        currentSourceEntity = [[DataManager sharedDataManager].sourcesArray objectAtIndex:menuSelectedIndex];
        [self loadWebviewWithSourceEntity:currentSourceEntity];
    }
    
}

- (void)loadWebviewWithSourceEntity:(SourceEntity*)sourceEntity {
    
    [Utils sendTrackWithCategory:@"User action" action:@"Change source" label:sourceEntity.title value:nil];
    [Utils sendTrackScreenViewName:sourceEntity.title];
    
    NSURL* url = [NSURL URLWithString:[sourceEntity defaultLink]];
    [webView loadRequest:[NSURLRequest requestWithURL:url]];
    self.title = sourceEntity.title;
    
    [self showLoadingView];
}

- (void)backButtonTouched {
    if([webView canGoBack]) {
        [webView goBack];
    }
}

//- (void)forwardButtonTouched {
//    if([webView canGoForward]) {
//        [webView goForward];
//    }
//}

- (void)actionButtonTouched {
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"Chọn hành động" delegate:self cancelButtonTitle:@"Hủy" destructiveButtonTitle:nil otherButtonTitles:@"Tải lại", @"Lên đầu trang", @"Xuống cuối trang", nil];
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    // refresh
    if(buttonIndex == 0) {
        [self refresh];
    }
    
    // go to top
    else if(buttonIndex == 1) {
        [webView.scrollView setContentOffset:CGPointZero animated:YES];
    }
    
    // go to bottom
    else if(buttonIndex == 2) {
        [webView.scrollView setContentOffset:CGPointMake(0, webView.scrollView.contentSize.height - 600) animated:YES];
    }
}

- (void)refresh {
    NSURL* currentURL = webView.request.URL;
    if(currentURL && currentURL.absoluteString.length > 0) {
        [webView loadRequest:[NSURLRequest requestWithURL:currentURL]];
        [self showLoadingView];
    }
    else {
        [self updateMenuSelectedIndexToCurrentIndex];
    }
}

- (void)webViewDidStartLoad:(UIWebView *)_webView {
    NSURL* currentURL = webView.request.URL;
    NSURL* defaultUrl = [NSURL URLWithString:[currentSourceEntity defaultLink]];
    
    if([self isMatchUrl:currentURL withOtherUrl:defaultUrl]) {
        backButtonItem.enabled = NO;
    }
    else {
        backButtonItem.enabled = [webView canGoBack];
    }
    
//    forwardButtonItem.enabled = [webView canGoForward];
}

- (void)webViewDidFinishLoad:(UIWebView *)_webView {
    [self hideLoadingView];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"didFailLoadWithError %@", error);
    
    if (error.code == NSURLErrorNotConnectedToInternet) {
        [self hideLoadingView];
        [self showRefreshView];
        [self.view makeToast:@"Không có kết nối. Vui lòng kết nối rồi nhấn nút Tải lại" duration:3 position:@"top"];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [DataManager sharedDataManager].sourcesArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MenuCell* cell = [tableView dequeueReusableCellWithIdentifier:kMenuRowIdentifier];
    if(cell == nil) {
        cell = [[MenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kMenuRowIdentifier];
    }
    SourceEntity* sourceEntity = [[DataManager sharedDataManager].sourcesArray objectAtIndex:indexPath.row];
    cell.textLabel.text = sourceEntity.title;
    
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:sourceEntity.iconString] placeholderImage:[UIImage imageNamed:@"menu_icon_default"]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.menuSelectedIndex = (int)indexPath.row;
    [self showHideMenu];
}

- (void)showLoadingView {
    [UIView animateWithDuration:0.2 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)hideLoadingView {
    [UIView animateWithDuration:0.2 animations:^{
        loadingView.alpha = 0;
    }];
}

- (void)refreshButtonTouched {
    [self updateMenuSelectedIndexToCurrentIndex];
    [self hideRefreshView];
    
}

- (void)showRefreshView {
    [UIView animateWithDuration:0.2 animations:^{
        refreshView.alpha = 1;
    }];
}

- (void)hideRefreshView {
    [UIView animateWithDuration:0.2 animations:^{
        refreshView.alpha = 0;
    }];
}

- (void)panGestureRecognizer:(UIGestureRecognizer*)gesture {
    CGPoint location = [gesture locationInView:self.view];
    
    if(gesture.state == UIGestureRecognizerStateBegan) {
        if(CGRectContainsPoint(CGRectMake(mainView.left - 30, 0, 60, mainView.height), location) || [self isMenuShowing]) {
            isDragging = YES;
        }
    }
    else if(gesture.state == UIGestureRecognizerStateChanged) {
        if(isDragging) {
            if(location.x < kMenuWidth && location.x >= 0) {
                CGRect mainViewFrame = mainView.frame;
                mainViewFrame.origin.x  = location.x;
                mainView.frame = mainViewFrame;
            }
        }
    }
    else if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled) {
        isDragging = NO;
        if(location.x > kMenuWidth/2) {
            [self showMenu];
        }
        else {
            [self hideMenu];
        }
    }
}

- (void)loadAd {
    GADRequest* request = [GADRequest request];
    // iP6: 34ba
    NSArray* devices = [NSArray arrayWithObjects:GAD_SIMULATOR_ID, @"32070a6c8ab91d07956b9a2db0a534ba",nil];
    request.testDevices = devices;
    [bannerView loadRequest:request];
}

- (void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error {
    NSLog(@"Fail to receive ad: %@", error);
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadAd];
    });
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    [self layoutViews];
}

- (BOOL)isMatchUrl:(NSURL *)url withOtherUrl:(NSURL*)otherUrl {
    
    // First condition

    NSString* host1 = url.host;
    if([host1 hasPrefix:kWwwPrefix]) {
        host1 = [host1 substringFromIndex:kWwwPrefix.length];
    }
    
    NSString* host2 = otherUrl.host;
    if([host2 hasPrefix:kWwwPrefix]) {
        host2 = [host2 substringFromIndex:kWwwPrefix.length];
    }
    
    if([host1 isEqualToString:host2] == NO) {
        return NO;
    }
    
    // Second condition
    
    NSString* path1 = url.path;
    if([path1 hasSuffix:@"/"]) {
        path1 = [path1 substringToIndex:path1.length - 1];
    }
    
    NSString* path2 = otherUrl.path;
    if([path2 hasSuffix:@"/"]) {
        path2 = [path2 substringToIndex:path2.length - 1];
    }
    
    if([path1 isEqual:path2] == NO) {
        return NO;
    }
    
    return YES;
}

@end
